/*
 * @Author: your name
 * @Date: 2021-05-11 22:16:07
 * @LastEditTime: 2021-05-11 22:27:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \studygo\锁\并发安全字典map\main.go
 */
package main

import (
	"fmt"
	"strconv"
	"sync"
)

//使用sync.Map并发添加数据
var waitGroup sync.WaitGroup
var syncMap sync.Map

func main() {
	routineSize := 5
	//让主线程等待添加完毕
	waitGroup.Add(routineSize)
	//并发添加数据
	for i := 0; i < routineSize; i++ {
		go addNumber(i * 10)
	}
	//开始等待
	waitGroup.Wait()
	var size int
	//统计数量
	syncMap.Range(func(key, value interface{}) bool {
		size++
		return true
	})
	fmt.Println("syncMap current size is " + strconv.Itoa(size))
	value, ok := syncMap.Load(0)
	if ok {
		fmt.Println("key 0 has value", value, " ")
	}
}

func addNumber(begin int) {
	//往syncMap中放入数据
	for i := begin; i < begin+3; i++ {
		syncMap.Store(i, 1)
	}
	//通知数据已经添加完毕
	waitGroup.Done()
}
